package com.action;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.model.SaleReturn;
import com.service.SaleReturnService;
import com.service.impl.SaleReturnServiceImpl;
import com.util.SerialNumberUtil;

@WebServlet("/SaleReturnController")
public class SaleReturnController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static SaleReturnService srs = new SaleReturnServiceImpl();
	private static SaleReturn saleReturn = new SaleReturn();

	public SaleReturnController() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method = request.getParameter("method");
		if ("addSaleReturn".equals(method)) {
			addSaleReturn(request, response);
		} else if ("selectSaleReturn".equals(method)) {
			selectSaleReturn(request, response);
		}
	}

	private void selectSaleReturn(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String saleOrderNo = request.getParameter("saleOrderNo");
		// SaleReturnService srs = new SaleReturnServiceImpl();
		response.getWriter().write(srs.selectSaleItem(saleOrderNo));
		response.getWriter().flush();
	}

	private void addSaleReturn(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int saleOrder_Id = srs.getSaleOrder_Id();
		String reason = request.getParameter("reason");
		Double total = Double.parseDouble(request.getParameter("total"));
		String handler = request.getParameter("handler");

		int saleReturnNum = srs.getLastNum() + 1;
		String saleReturnNo = SerialNumberUtil.getSerialNumber("return",
				saleReturnNum);

		// SaleReturn saleReturn = new SaleReturn();
		saleReturn.setSaleReturnNo(saleReturnNo);
		saleReturn.setSaleOrder_Id(saleOrder_Id);
		saleReturn.setReason(reason);
		saleReturn.setTotal(total);
		saleReturn.setDate(new Date());
		saleReturn.setHandler(handler);

		boolean b = srs.addSaleReturn(saleReturn);
		String resultJson = null;
		if (b) {
			resultJson = "{\"success\":true,\"msg\":\"退货完成！\"}";
		} else {
			resultJson = "{\"success\":false,\"msg\":\"退货失败，请重试!\"}";
		}
		response.getWriter().print(resultJson);
		response.getWriter().flush();
	}

}
